Data Transfer Objects

If you have to go across application boundaries you will need a way to serialize the data of a Data Object. Then you can use Data Transfer Objects. Data Transfer Objects contain only the serializable data of a Data Object.


If you select the checkbox Generate Data Transfer Objects in the Project tab, an additional class with suffix “DTO” is created. The DTO classes are generated in the namespace “<Your namespace>.DataTransferObjects”, so you can put them in their own assembly to share them between two applicactions.


You can create a Data Transfer Object with the method GetDTO and apply its data to a Data Object by using the method SetDTO:

EmployeeDTO dto = employee1.GetDTO();


employee2.SetDTO(dto);



Xml serialization


First create a Data Transfer Object and then use the XmlSerializer class:


Employee e = Employee.Get(1);

EmployeeDTO dto = e.GetDTO();


XmlSerializer s = new XmlSerializer(typeof(EmployeeDTO));

FileStream f = File.Create(@"c:\temp\test.xml");

s.Serialize(f, dto);

f.Close();



Xml deserialization


Xml deserialization is almost as easy as serialization, with one addition: You should call the method RefreshState of each object to ensure that the internal flags of the Data Object are refreshed. After that, you can for example call the Persist method to store it:


FileStream f = File.OpenRead(@"c:\temp\test.xml");

XmlSerializer s = new XmlSerializer(typeof(EmployeeDTO));

EmployeeDTO dto = (EmployeeDTO)s.Deserialize(f);

f.Close();


Employee e = new Employee();

e.SetDTO(dto);


e.RefreshState();



Soap-/Binary serialization


The serialization of Data Transfer Objects works with SoapFormatter and BinaryFormatter also. So if you work with web services or .Net Remoting, use the Data Transfer Objects as parameters of your methods. As the SoapFormatter does not support serialization of generic types (so in particular Nullables) the nullable types are stored internally as value types with a bool member to indicate a value.